<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="page.param.name" placeholder="关键字查询" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="info" icon="el-icon-edit" @click="handleCreate">
        新增
      </el-button>
      <el-button :loading="loading" class="filter-item" style="margin-left: 10px;" type="danger" icon="el-icon-delete" @click="deleteUser">
        删除
      </el-button>
      <el-button :loading="passwordLoading" class="filter-item" style="margin-left: 10px;" type="warning" icon="el-icon-edit" @click="restUserPassword">
        密码重置
      </el-button>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      height="500"
      highlight-current-row
      @selection-change="handleSelectionChange"
    >
      <el-table-column align="center" type="selection" width="55" />
      <el-table-column align="center" label="序号" type="index" width="50" />
      <el-table-column align="center" label="昵称" prop="name"/>
      <el-table-column align="center" label="账号" width="300" prop="account" />
      <el-table-column align="center" label="创建时间" width="200">
        <template slot-scope="scope">
          <i class="el-icon-time" />
          <span>{{ scope.row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" width="200" label="操作">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="viewClick(scope.row)">查看</el-button>
          <el-button type="text" size="small" @click="editClick(scope.row)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination v-show="page.total>0" :total="page.total" :current-page="page.page" :page-size="page.limit" @current-change="fetchData" />
    <el-dialog title="管理员" :visible.sync="dialogFormVisible">
      <el-form ref="form" :model="form" :rules="registerRules">
        <el-form-item label="昵称" label-width="150px" prop="name">
          <el-input
            ref="name"
            v-model="form.name"
            :readonly="state==='view'"
            placeholder="请输入昵称"
            name="name"
            type="text"
            tabindex="1"
            auto-complete="on"
          />
        </el-form-item>
        <el-form-item label="账号" label-width="150px" prop="account">
          <el-input
            ref="account"
            v-model="form.account"
            :readonly="state==='view'"
            placeholder="请输入账号"
            name="account"
            type="text"
            tabindex="1"
            auto-complete="on"
          />
        </el-form-item>
        <el-form-item v-if="state==='add'" label="密码" label-width="150px" prop="password">
          <el-input
            ref="password"
            v-model="form.password"
            placeholder="请输入密码"
            name="password"
            type="password"
            tabindex="1"
            auto-complete="on"
          />
        </el-form-item>
        <el-form-item v-if="state==='add'" label="确认密码" label-width="150px" prop="r_password">
          <el-input
            ref="r_password"
            v-model="form.r_password"
            placeholder="请再次输入密码"
            name="r_password"
            type="password"
            tabindex="1"
            auto-complete="on"
          />
        </el-form-item>
      </el-form>
      <div v-if="state!=='view'" slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { page, add, edit, deleteByIds, restPassword } from '@/api/user'
import { validNotNull, validUsername } from '@/utils/validate'
import { Message } from 'element-ui'
import { mapGetters } from 'vuex'

export default {
  data() {
    const validateName = (rule, value, callback) => {
      if (!validNotNull(value)) {
        callback(new Error('请输入要新增的用户昵称'))
      } else {
        callback()
      }
    }
    const validateUserName = (rule, value, callback) => {
      if (!validUsername(value)) {
        callback(new Error('请输入要新增的账号，长度不能小于11位'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('密码长度的要大于6位'))
      } else {
        callback()
      }
    }
    const validateTwoPassword = (rule, value, callback) => {
      if (value !== this.form.password) {
        callback(new Error('两次密码输入不一致'))
      } else {
        callback()
      }
    }
    return {
      list: null,
      listLoading: true,
      loading: false,
      passwordLoading: false,
      page: {
        page: 1,
        size: 10,
        total: 0,
        param: { name: '' }
      },
      multipleSelection: [],
      dialogFormVisible: false,
      state: 'add',
      form: {
        account: '',
        name: '',
        password: '',
        r_password: ''
      },
      registerRules: {
        name: [{ required: true, trigger: 'blur', validator: validateName }],
        account: [{ required: true, trigger: 'blur', validator: validateUserName }],
        password: [{ required: true, trigger: 'blur', validator: validatePassword }],
        r_password: [{ required: true, trigger: 'blur', validator: validateTwoPassword }]
      }
    }
  },
  computed: {
    ...mapGetters([
      'name'
    ])
  },
  created() {
    this.fetchData()
  },
  methods: {
    // 获取列表数据
    fetchData(val) {
      if (val != null && val !== '') {
        this.page.page = val
      }
      this.listLoading = true
      page(this.page).then(response => {
        this.list = response.result.records
        this.page.total = response.result.total
        this.listLoading = false
      })
    },
    // 选中改变
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 列表筛选
    handleFilter() {
      this.fetchData()
    },
    // 新增方法
    submit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.state === 'add') {
            add(this.form).then(res => {
              if (res.code === '200'){
                this.dialogFormVisible = false
                this.fetchData()
                Message.success(res.result)
              }
            }).catch((err) => {
              console.log(err)
            })
          } else {
            edit(this.form).then(res => {
              if (res.code === '200') {
                this.dialogFormVisible = false
                this.form = {
                  account: '',
                  name: '',
                  password: '',
                  r_password: ''
                }
                this.fetchData()
                Message.success(res.result)
              }
            }).catch((err) => {
              console.log(err)
            })
          }
        } else {
          return false
        }
      })
    },
    // 新增
    handleCreate() {
      this.dialogFormVisible = true
      this.state = 'add'
      this.form = {
        account: '',
        name: '',
        password: '',
        r_password: ''
      }
    },
    // 查看
    viewClick(data) {
      this.state = 'view'
      this.dialogFormVisible = true
      this.form = data
    },
    // 修改
    editClick(data) {
      this.dialogFormVisible = true
      this.state = 'edit'
      this.form.id = data.id
      this.form.account = data.account
      this.form.name = data.name
    },
    // 删除
    deleteUser() {
      this.loading = true
      const ids = []
      if (this.multipleSelection.length > 0) {
        this.multipleSelection.forEach(item => {
          ids.push(item.id)
        })
        deleteByIds(ids).then(res => {
          this.loading = false
          if (res.code === '200') {
            this.fetchData()
            Message.success(res.result)
          }
        }).catch((err) => {
          this.loading = false
          console.log(err)
        })
      } else {
        this.loading = false
        Message.error('请要修改的数据！')
      }
    },
    // 密码重置
    restUserPassword() {
      this.passwordLoading = true
      const ids = []
      if (this.multipleSelection.length > 0) {
        this.multipleSelection.forEach(item => {
          ids.push(item.id)
        })
        restPassword(ids).then(res => {
          this.passwordLoading = false
          if (res.code === '200') {
            this.fetchData()
            Message.success(res.result)
          }
        }).catch((err) => {
          this.passwordLoading = false
          console.log(err)
        })
      } else {
        this.passwordLoading = false
        Message.error('请要修改的数据！')
      }
    }
  }
}
</script>
